'use strict';

const Service = require('egg').Service;

class IdleTransferService extends Service {
  async create(data) {
    const { ctx } = this;
    return await ctx.model.IdleTransfer.create(data);
  }

  async update(id, data) {
    const { ctx } = this;
    const transfer = await ctx.model.IdleTransfer.findByPk(id);
    if (!transfer) {
      ctx.throw(404, '调拨记录不存在');
    }
    return await transfer.update(data);
  }

  async deleteById(id) {
    const { ctx } = this;
    const transfer = await ctx.model.IdleTransfer.findByPk(id);
    if (!transfer) {
      ctx.throw(404, '调拨记录不存在');
    }
    return await transfer.destroy();
  }

  async findOne(id) {
    const { ctx } = this;
    return await ctx.model.IdleTransfer.findByPk(id, {
      include: [{
        model: ctx.model.IdleItem,
        attributes: ['id', 'code', 'name', 'specification', 'unit', 'quantity', 'condition', 'status']
      }]
    });
  }

  async getPage(where, page, size) {
    const { ctx } = this;
    const { createTimeSort } = this.ctx.query
    let order = []
    if (createTimeSort) {
      order = [
        'apply_time', createTimeSort
      ]
    }
    const { count, rows } = await ctx.model.IdleTransfer.findAndCountAll({
      where,
      offset: (page - 1) * size,
      limit: size,
      order,
      include: [{
        model: ctx.model.IdleItem,
      }]
    });
    return { count, rows };
  }

  async allList(where) {
    const { ctx } = this;
    return await ctx.model.IdleTransfer.findAll({
      where,
      order: [['create_time', 'DESC']],
      include: [{
        model: ctx.model.IdleItem,
        attributes: ['id', 'code', 'name', 'specification', 'unit', 'condition', 'status']
      }]
    });
  }

  async simpleList(where) {
    const { ctx } = this;
    return await ctx.model.IdleTransfer.findAll({
      where,
      attributes: ['id', 'item_id', 'from_project_id', 'to_project_id', 'quantity', 'status', 'apply_time'],
      order: [['create_time', 'DESC']]
    });
  }

  async apply(data) {
    const { ctx } = this;
    const { item_id, quantity } = data;

    // 检查物资/设备是否存在
    const item = await ctx.model.IdleItem.findByPk(item_id);
    if (!item) {
      ctx.throw(404, '物资/设备不存在');
    }

    // 检查数量是否合法
    if (parseFloat(quantity) <= 0 || parseFloat(quantity) > parseFloat(item.quantity)) {
      ctx.throw(400, '调拨数量不合法');
    }
    console.log('item.rental_price',item.rental_price)
    // 计算调拨金额
    if (item.rental_price && !isNaN(Number(item.rental_price))) {
      let transfer_price = parseFloat(item.rental_price) * parseFloat(quantity) * parseFloat(item.discount_rate) / 100;
      if (!isNaN(transfer_price)) {
        data.transfer_price = transfer_price
      }
    }
    data.category_id = item.category_id;
    data.category_name = item.category_name;
    data.type = item.type
    data.province = item.province
    data.city = item.city
    data.address = item.address
    data.approve_user_id = item.create_user_id
    data.approve_user_name = item.create_user_name
    console.log('data',data)
    // 创建调拨记录
    const transfer = await this.create(data);
    // 更新物资/设备状态为已预定
    await item.update({
      quantity: Number(item.quantity) - Number(transfer.quantity),
    });

    return transfer;
  }

  async approve({  id, status, remark, approved_user_id, approved_user_name }) {
    const { ctx } = this;
    const transfer = await this.findOne(id);
    if (!transfer) {
      ctx.throw(404, '调拨记录不存在');
    }

    // 检查状态是否为待审批
    if (transfer.status !== 'pending') {
      ctx.throw(400, '该调拨记录已处理，不能重复审批');
    }

    // 更新调拨记录
    const updateData = {
      status,
      approved_user_id,
      approved_user_name,
      approve_time: new Date(),
      approve_remark: remark || '同意'
    };

    await transfer.update(updateData);

    // 如果拒绝，将物资/设备状态恢复为可用
    if (status === 'rejected') {
      const item = await ctx.model.IdleItem.findByPk(transfer.item_id);
      if (item) {
        await item.update({
          status: 'available',
          quantity: Number(item.quantity) + Number(transfer.quantity),
        });
      }
    }

    return transfer;
  }

  async complete(id) {
    const { ctx } = this;
    const transfer = await this.findOne(id);
    if (!transfer) {
      ctx.throw(404, '调拨记录不存在');
    }

    // 检查状态是否为已同意
    if (transfer.status !== 'approved') {
      ctx.throw(400, '该调拨记录状态不正确，不能完成调拨');
    }

    // 更新调拨记录
    const updateData = {
      status: 'completed',
      complete_time: new Date()
    };

    await transfer.update(updateData);

    // 更新物资/设备信息
    const item = await ctx.model.IdleItem.findByPk(transfer.item_id);
    if (item) {
      // 如果全部调拨，则更新项目信息和状态
      if (parseFloat(transfer.quantity) >= parseFloat(item.quantity)) {
        await item.update({
          project_id: transfer.to_project_id,
          project_name: transfer.to_project_name,
          status: 'transferred'
        });
      } else {
        // 部分调拨，减少原物资数量
        const remainingQuantity = parseFloat(item.quantity) - parseFloat(transfer.quantity);
        await item.update({
          quantity: remainingQuantity,
          total_price: parseFloat(item.unit_price) * remainingQuantity,
          status: 'available'
        });

        // 创建新的物资记录
        const newItemData = {
          ...item.toJSON(),
          id: undefined,
          quantity: transfer.quantity,
          total_price: parseFloat(item.unit_price) * parseFloat(transfer.quantity),
          project_id: transfer.to_project_id,
          project_name: transfer.to_project_name,
          status: 'transferred',
          create_time: new Date(),
          update_time: new Date()
        };

        await ctx.model.IdleItem.create(newItemData);
      }
    }

    return transfer;
  }

  async cancel(id) {
    const { ctx } = this;
    const transfer = await this.findOne(id);
    console.log('transfer',transfer)
    if (!transfer) {
      ctx.throw(404, '调拨记录不存在');
    }

    // 检查状态是否为待审批或已同意
    if (transfer.status !== 'pending') {
      ctx.throw(400, '该调拨记录状态不正确，不能取消');
    }

    // 更新调拨记录
    const updateData = {
      status: 'canceled'
    };
    console.log('updateData',updateData)
    await transfer.update(updateData);

    // 恢复物资/设备状态为可用
    const item = await ctx.model.IdleItem.findByPk(transfer.item_id);
    if (item) {
      await item.update({
        status: 'available',
        quantity: Number(item.quantity) + Number(transfer.quantity),
      });
    }

    return transfer;
  }

  async getMyApplies(userId, query) {
    const { ctx } = this;
    const where = { apply_user_id: userId };

    if (query.status) {
      where.status = query.status;
    }

    return await this.getPage(where, query.pageNum || 1, query.pageSize || 10);
  }

  async getMyApprovals(userId, query) {
    const { ctx } = this;
    // 查找用户所属的项目
    const userProjects = await ctx.model.IdleItem.findAll({
      attributes: ['project_id'],
      where: { create_user_id: userId },
      group: ['project_id']
    });

    const projectIds = userProjects.map(item => item.project_id);

    const where = {
      from_project_id: {
        [ctx.app.Sequelize.Op.in]: projectIds
      }
    };

    if (query.status) {
      where.status = query.status;
    }

    return await this.getPage(where, query.pageNum || 1, query.pageSize || 10);
  }

  async getStatistics(startDate, endDate, project_id) {
    const { ctx } = this;
    const where = {};

    if (startDate && endDate) {
      where.apply_time = {
        [ctx.app.Sequelize.Op.between]: [startDate, endDate]
      };
    }

    if (project_id) {
      where[ctx.app.Sequelize.Op.or] = [
        { from_project_id: project_id },
        { to_project_id: project_id }
      ];
    }

    // 按状态统计
    const statusStats = await ctx.model.IdleTransfer.findAll({
      attributes: [
        'status',
        [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count'],
        [ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('transfer_price')), 'value']
      ],
      where,
      group: ['status']
    });

    // 按项目统计
    const projectStats = await ctx.model.IdleTransfer.findAll({
      attributes: [
        'from_project_id',
        'from_project_name',
        [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count'],
        [ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('transfer_price')), 'value']
      ],
      where,
      group: ['from_project_id', 'from_project_name']
    });

    // 按月份统计
    const monthStats = await ctx.model.IdleTransfer.findAll({
      attributes: [
        [ctx.app.Sequelize.fn('DATE_FORMAT', ctx.app.Sequelize.col('apply_time'), '%Y-%m'), 'month'],
        [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count'],
        [ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('transfer_price')), 'value']
      ],
      where,
      group: ['month'],
      order: [[ctx.app.Sequelize.literal('month'), 'ASC']]
    });

    return {
      statusStats,
      projectStats,
      monthStats
    };
  }
}

module.exports = IdleTransferService;
